package com.thb.pay.core.interceptor;

import com.thb.pay.core.annotation.LoginRequired;
import com.thb.pay.core.enums.Action;
import com.thb.pay.core.enums.ExceptionEnum;
import com.thb.pay.core.exception.RRException;
import com.thb.pay.core.utils.Constant;
import com.thb.pay.core.utils.ContextHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 登入校验
 */

public abstract class AbstractAuthenticationInterceptor implements HandlerInterceptor {

    protected static final Logger logger = LoggerFactory.getLogger(AbstractAuthenticationInterceptor.class);

    /**
     * @param request
     * @param response
     * @param handler
     * @return
     * @方法名称
     * @功能描述 登入校验逻辑
     * @作者: lucky
     * @创建时间: 14:22 2019/10/11
     * @版本 v1.01
     **/
    public abstract boolean authentication(HttpServletRequest request, HttpServletResponse response, Object handler);


    protected String getToken(HttpServletRequest request) {
        String token = request.getHeader(Constant.HEADER_TOKEN);
        return token;
    }
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 如果不是映射到方法直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        /**
         *  检查是否有 LoginRequired 注释，Action.Skip
         */
        if (method.isAnnotationPresent(LoginRequired.class)) {
            LoginRequired required = method.getAnnotation(LoginRequired.class);
            if (required.value().equals(Action.Skip)) {
                return true;
            }
        }
        if (StringUtils.isEmpty(getToken(request))) {
            throw RRException.build(ExceptionEnum.TOKEN_ILLEGAL);
        }
        return authentication(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest,
                           HttpServletResponse httpServletResponse,
                           Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Object o, Exception e) throws Exception {
        if (logger.isDebugEnabled()) {
            logger.debug("clean>>>>>>>>>>>>>>>>>>>>>context user info.");
        }
        ContextHolder.removeCurrentContextMap();
    }

}